// useCountdown.js 或 useCountdown.ts（如果你用 TypeScript）
import { useEffect, useRef, useState } from "react";

export function useCountdown(initialTime = 60) {
  const [time, setTime] = useState(initialTime);
  const timerRef = useRef(null);

  const start = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    setTime(initialTime);
    timerRef.current = setInterval(() => {
      setTime((prev) => {
        if (prev <= 1) {
          clearInterval(timerRef.current);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const reset = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    setTime(initialTime);
  };

  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  return { time, start, reset };
}
